import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.*;

/**
 * @author zhangshuw
 * <p>     2019/8/9
 */
public class Main {

    public static void main(String[] args) {
        if (args.length <= 6) {
            System.err.println("usage: [host:port/database user password [update/query] sql/[-f absoluteFilePath]]");
            return;
        }
        System.out.println("---------------------------------");
        StringBuilder sql = new StringBuilder(args[4]);
        if ("-f".equals(sql.toString())) {
            try {
                sql = new StringBuilder(new String(Files.readAllBytes(Paths.get(args[5])), StandardCharsets.UTF_8));
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
            System.out.println("file:");
            System.out.println(args[5]);
        } else {
            for (int i = 5; i < args.length; i++) {
                sql.append(" ").append(args[i]);
            }
            System.out.println("sql:");
            System.out.println(sql);
        }
        System.out.println();
        System.out.println("result: ");
        try {
            Connection conn = JdbcUtil.instance.user(args[1]).password(args[2]).host(args[0]).getConnection();
            PreparedStatement ps = conn.prepareStatement(sql.toString());
            if ("update".equals(args[3])) {
                System.out.println(ps.executeUpdate());
                JdbcUtil.close(ps, conn);
            } else if ("query".equals(args[3])) {
                ResultSet rs = ps.executeQuery();
                ResultSetMetaData md = rs.getMetaData();
                int columnCount = md.getColumnCount();
                for (int i = 1; i <= columnCount; i++) {
                    System.out.print(md.getColumnName(i));
                    System.out.print("  ");
                }
                System.out.println();
                while (rs.next()) {
                    for (int i = 1; i <= columnCount; i++) {
                        System.out.print(rs.getObject(i));
                        System.out.print("  ");
                    }
                    System.out.println();
                }
                JdbcUtil.close(rs, ps, conn);
            }
            System.out.println();
            System.out.println("---------------------------------");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
